//
//  DatePickerDialogView.swift
//  UserApp_iOS
//
//  Created by linlin on 2019/9/18.
//  Copyright © 2019 linlin. All rights reserved.
//

import Foundation
import UIKit
class DatePickerDialogView: BaseDialogView, DialogDataSource {
    typealias Confirm = ((Date)->Void)
    typealias Cancel = (()->Void)
    private var confirmHandler: Confirm?
    private var cancelHandler: Cancel?
    private var datePicker: UIDatePicker!
    private var currentDate: Date?
    
    init(confirmHandler: Confirm?, cancelHandler: Cancel?) {
        super.init(style: .actionsheet)
        self.dataSource = self
        self.confirmHandler = confirmHandler
        self.cancelHandler = cancelHandler
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    func dialogContentView() -> UIView {
        let containerView: UIView = UIView(frame: CGRect(x: 0, y: screenHeight-200, width: screenWidth, height: 200))
        containerView.backgroundColor = .white
        
        datePicker = UIDatePicker(frame: CGRect(x: 0, y: 30, width: screenWidth, height: 170))
        datePicker.locale = Locale(identifier: "zh_CN")
        datePicker.addTarget(self, action: #selector(dateChangedAction(sender:)), for: .valueChanged)
        currentDate = datePicker.date
        
        let cancelBtn: UIButton = UIButton(type: .custom)
        cancelBtn.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
        cancelBtn.setTitle("取消", for: .normal)
        cancelBtn.setTitleColor(.blue, for: .normal)
        cancelBtn.tag = 1
        cancelBtn.addTarget(self, action: #selector(buttonsAction(sender:)), for: .touchUpInside)
        
        let confirmBtn: UIButton = UIButton(type: .custom)
        confirmBtn.frame = CGRect(x: 0, y: 0, width: 60, height: 30)
        confirmBtn.right = containerView.width
        confirmBtn.setTitle("确定", for: .normal)
        confirmBtn.setTitleColor(.red, for: .normal)
        confirmBtn.tag = 2
        confirmBtn.addTarget(self, action: #selector(buttonsAction(sender:)), for: .touchUpInside)

        containerView.addSubview(cancelBtn)
        containerView.addSubview(confirmBtn)
        containerView.addSubview(datePicker)
        datePicker.datePickerMode = .date
        return containerView
    }
    
    @objc func buttonsAction(sender: UIButton) -> Void{
        if sender.tag == 1{
            cancelHandler?()
        } else {
            confirmHandler?(currentDate!)
        }
        dismiss()
    }
    
    @objc func dateChangedAction(sender: UIDatePicker){
        currentDate = sender.date
    }
}
